<template>
    <div class="container">
        <div class="page-header">
            <div class="back-button">
                <router-link to="/main/xingzheng/gudingzichan">
                    <el-button type="primary" icon="el-icon-back">返回</el-button>
                </router-link>
            </div>
            <h1>固定资产转移单</h1>
        </div>

        <div class="main-content">
            <div class="form-actions" v-if="!isViewMode">
                <el-button type="primary" @click="saveData">保存</el-button>
                <router-link to="/main/xingzheng/gdzczhuanyi/gdzczhuanyiList">
                    <el-button type="primary">列表</el-button>
                </router-link>
            </div>
            <el-form :model="formData" class="investigation-form">
                <p style="text-align:left">NO：<el-input style="width: 200px;" v-model="formData.transferNo"
                        :disabled="isViewMode" /></p>
                <div class="checkbox-group">
                    <label><el-checkbox v-model="formData.isEquipment" :disabled="isViewMode"> 设备</el-checkbox></label>
                    <label><el-checkbox v-model="formData.isInstrument" :disabled="isViewMode"> 仪器</el-checkbox></label>
                    <label><el-checkbox v-model="formData.isFixture" :disabled="isViewMode"> 治具</el-checkbox></label>
                    <label><el-checkbox v-model="formData.isTool" :disabled="isViewMode"> 工具</el-checkbox></label>
                    <label><el-checkbox v-model="formData.isOther" :disabled="isViewMode"> 其它</el-checkbox></label>
                </div>
                <table border="1">
                    <tr>
                        <td>申请单位</td>
                        <td><el-input v-model="formData.applicationUnit" :disabled="isViewMode" /></td>
                        <td>申请日期</td>
                        <td>
                            <!-- 使用格式化后的日期 -->
                            <el-input v-model="formattedApplicationDate.year" type="number" style="width: 80px;"
                                :disabled="isViewMode" /> 年
                            <el-input v-model="formattedApplicationDate.month" type="number" style="width: 60px;"
                                :disabled="isViewMode" /> 月
                            <el-input v-model="formattedApplicationDate.day" type="number" style="width: 60px;"
                                :disabled="isViewMode" /> 日
                        </td>
                        <td>资产名称</td>
                        <td><el-input v-model="formData.assetName" :disabled="isViewMode" /></td>
                    </tr>
                    <tr>
                        <td>资产编号</td>
                        <td><el-input v-model="formData.assetNumber" :disabled="isViewMode" /></td>
                        <td>型 号</td>
                        <td><el-input v-model="formData.model" :disabled="isViewMode" /></td>
                        <td>规 格</td>
                        <td><el-input v-model="formData.specification" :disabled="isViewMode" /></td>
                    </tr>
                    <tr>
                        <td>存放地点</td>
                        <td><el-input v-model="formData.storageLocation" :disabled="isViewMode" /></td>
                        <td>希望移转日期</td>
                        <td colspan="3">
                            <!-- 使用格式化后的日期 -->
                            <el-input v-model="formattedTransferDate.year" type="number" style="width: 80px;"
                                :disabled="isViewMode" /> 年
                            <el-input v-model="formattedTransferDate.month" type="number" style="width: 60px;"
                                :disabled="isViewMode" /> 月
                            <el-input v-model="formattedTransferDate.day" type="number" style="width: 60px;"
                                :disabled="isViewMode" /> 日
                        </td>
                    </tr>
                    <tr>
                        <td>移转原因</td>
                        <td colspan="6">
                            <el-input type="textarea" v-model="formData.transferReason" :disabled="isViewMode"
                                :rows="3" />
                        </td>
                    </tr>
                    <tr>
                        <td>移转方式</td>
                        <td colspan="6"><el-input v-model="formData.transferMethod" :disabled="isViewMode" /></td>
                    </tr>
                </table>
                <h3>移出单位</h3>
                <table border="1">
                    <tr>
                        <td>部 门</td>
                        <td><el-input v-model="formData.outDepartment" :disabled="isViewMode" /></td>
                        <td>原保管人</td>
                        <td><el-input v-model="formData.originalCustodian" :disabled="isViewMode" /></td>
                    </tr>
                    <tr>
                        <td>部门主管</td>
                        <td><el-input v-model="formData.outDepartmentSupervisor" :disabled="isViewMode" /></td>
                        <td>经 理</td>
                        <td><el-input v-model="formData.outManager" :disabled="isViewMode" /></td>
                    </tr>
                    <tr>
                        <td>部长/总监</td>
                        <td><el-input v-model="formData.outDirector" :disabled="isViewMode" /></td>
                    </tr>
                </table>
                <h3>接管单位</h3>
                <table border="1">
                    <tr>
                        <td>部 门</td>
                        <td><el-input v-model="formData.inDepartment" :disabled="isViewMode" /></td>
                        <td>新保管人</td>
                        <td><el-input v-model="formData.newCustodian" :disabled="isViewMode" /></td>
                    </tr>
                    <tr>
                        <td>部门主管</td>
                        <td><el-input v-model="formData.inDepartmentSupervisor" :disabled="isViewMode" /></td>
                        <td>经 理</td>
                        <td><el-input v-model="formData.inManager" :disabled="isViewMode" /></td>
                    </tr>
                    <tr>
                        <td>部长/总监</td>
                        <td><el-input v-model="formData.inDirector" :disabled="isViewMode" /></td>
                    </tr>
                </table>
                <h3>意见及审查</h3>
                <table border="1">
                    <tr>
                        <td>总经理意见</td>
                        <td>
                            <el-input type="textarea" v-model="formData.generalManagerOpinion" :disabled="isViewMode"
                                :rows="3" />
                        </td>
                        <td>财务管理部意见</td>
                        <td>
                            <el-input type="textarea" v-model="formData.financeDepartmentOpinion" :disabled="isViewMode"
                                :rows="3" />
                        </td>
                    </tr>
                    <tr>
                        <td>企业管理部审查</td>
                        <td>
                            <el-input type="textarea" v-model="formData.enterpriseManagementReview"
                                :disabled="isViewMode" :rows="3" />
                        </td>
                        <td>总裁/董事长</td>
                        <td><el-input v-model="formData.presidentOpinion" :disabled="isViewMode" /></td>
                    </tr>
                </table>
            </el-form>

            <div class="form-footer">
                <p>表单编号及版本：AM-JY-176 A/2 </p><span>保存期限：长期</span>
            </div>
        </div>
    </div>
</template>

<script>
import { saveFixedAssetTransfer, getFixedAssetTransferDetail } from '@/api/fixedAssetTransfer'
import { formatDate } from '@/utils/date'

export default {
    data() {
        return {
            isViewMode: false,
            formData: {
                id: null,
                transferNo: '',
                isEquipment: false,
                isInstrument: false,
                isFixture: false,
                isTool: false,
                isOther: false,
                applicationUnit: '',
                applicationDate: {
                    year: new Date().getFullYear(),  // 默认当前年
                    month: new Date().getMonth() + 1,  // 默认当前月
                    day: new Date().getDate()  // 默认当前日
                },
                assetName: '',
                assetNumber: '',
                model: '',
                specification: '',
                storageLocation: '',
                transferDate: {
                    year: new Date().getFullYear(),
                    month: new Date().getMonth() + 1,
                    day: new Date().getDate()
                },
                transferReason: '',
                transferMethod: '',
                outDepartment: '',
                originalCustodian: '',
                outDepartmentSupervisor: '',
                outManager: '',
                outDirector: '',
                inDepartment: '',
                newCustodian: '',
                inDepartmentSupervisor: '',
                inManager: '',
                inDirector: '',
                generalManagerOpinion: '',
                financeDepartmentOpinion: '',
                enterpriseManagementReview: '',
                presidentOpinion: ''
            },
            formattedApplicationDate: {},
            formattedTransferDate: {}
        };
    },
    created() {
        // 如果路由参数中有id，则获取详情数据
        const id = this.$route.query.id
        const mode = this.$route.query.mode || 'add' // 默认为新增模式

        // 设置查看模式
        this.isViewMode = mode === 'view'

        if (id) {
            this.getDetail(id)
        } else {
            // 初始化格式化后的日期
            this.formatDates()
        }
    },
    methods: {
        // 验证日期是否有效
        isValidDate(year, month, day) {
            if (!year || !month || !day) return false

            // 确保年份在合理范围内（例如1900-2100）
            if (year < 1900 || year > 2100) return false

            // 确保月份在1-12之间
            if (month < 1 || month > 12) return false

            // 获取指定年月的最后一天
            const lastDay = new Date(year, month, 0).getDate()

            // 确保日期在1到当月最后一天之间
            if (day < 1 || day > lastDay) return false

            return true
        },

        // 格式化日期对象为字符串
        formatDateToString(dateObj) {
            if (!dateObj || !this.isValidDate(dateObj.year, dateObj.month, dateObj.day)) {
                return null
            }
            return `${String(dateObj.year).padStart(4, '0')}-${String(dateObj.month).padStart(2, '0')}-${String(dateObj.day).padStart(2, '0')}`
        },

        // 表单验证
        validateForm() {
            if (!this.formData.assetName) {
                this.$message.warning('请输入资产名称')
                return false
            }
            if (!this.formData.assetNumber) {
                this.$message.warning('请输入资产编号')
                return false
            }
            if (!this.formData.outDepartment) {
                this.$message.warning('请输入移出部门')
                return false
            }
            if (!this.formData.inDepartment) {
                this.$message.warning('请输入接管部门')
                return false
            }

            // 验证申请日期
            if (!this.isValidDate(
                this.formattedApplicationDate.year,
                this.formattedApplicationDate.month,
                this.formattedApplicationDate.day
            )) {
                this.$message.warning('申请日期无效')
                return false
            }

            // 验证移转日期
            if (!this.isValidDate(
                this.formattedTransferDate.year,
                this.formattedTransferDate.month,
                this.formattedTransferDate.day
            )) {
                this.$message.warning('移转日期无效')
                return false
            }

            return true
        },

        // 保存数据
        async saveData() {
            if (!this.validateForm()) {
                return
            }

            try {
                const submitData = { ...this.formData }

                // 处理资产类型
                submitData.assetType = [
                    submitData.isEquipment && '设备',
                    submitData.isInstrument && '仪器',
                    submitData.isFixture && '治具',
                    submitData.isTool && '工具',
                    submitData.isOther && '其它'
                ].filter(Boolean).join(',')

                // 格式化申请日期
                submitData.applicationDate = this.formatDateToString(this.formattedApplicationDate)
                if (!submitData.applicationDate) {
                    this.$message.warning('申请日期格式错误')
                    return
                }

                // 格式化移转日期
                submitData.transferDate = this.formatDateToString(this.formattedTransferDate)
                if (!submitData.transferDate) {
                    this.$message.warning('移转日期格式错误')
                    return
                }

                await saveFixedAssetTransfer(submitData)
                this.$message.success('保存成功')
                // 返回列表页
                this.$router.push('/main/xingzheng/gdzczhuanyi/gdzczhuanyiList')
            } catch (error) {
                this.$message.error('保存失败：' + (error.message || '未知错误'))
            }
        },

        // 获取详情数据
        async getDetail(id) {
            try {
                const response = await getFixedAssetTransferDetail(id)
                if (response.data) {
                    const data = response.data

                    // 处理资产类型
                    if (data.assetType) {
                        const types = data.assetType.split(',')
                        data.isEquipment = types.includes('设备')
                        data.isInstrument = types.includes('仪器')
                        data.isFixture = types.includes('治具')
                        data.isTool = types.includes('工具')
                        data.isOther = types.includes('其它')
                    }

                    // 处理申请日期
                    if (data.applicationDate) {
                        try {
                            const [year, month, day] = data.applicationDate.split('-')
                            data.applicationDate = {
                                year: parseInt(year),
                                month: parseInt(month),
                                day: parseInt(day)
                            }
                        } catch (e) {
                            data.applicationDate = {
                                year: new Date().getFullYear(),
                                month: new Date().getMonth() + 1,
                                day: new Date().getDate()
                            }
                        }
                    }

                    // 处理移转日期
                    if (data.transferDate) {
                        try {
                            const [year, month, day] = data.transferDate.split('-')
                            data.transferDate = {
                                year: parseInt(year),
                                month: parseInt(month),
                                day: parseInt(day)
                            }
                        } catch (e) {
                            data.transferDate = {
                                year: new Date().getFullYear(),
                                month: new Date().getMonth() + 1,
                                day: new Date().getDate()
                            }
                        }
                    }

                    this.formData = { ...this.formData, ...data }
                    // 格式化日期
                    this.formatDates()
                }
            } catch (error) {
                this.$message.error('获取数据失败')
            }
        },

        handleEdit() {
            // 切换到编辑模式
            this.$router.push({
                path: '/main/xingzheng/gdzczhuanyi/gdzczhuanyi',
                query: {
                    id: this.$route.query.id,
                    mode: 'edit'
                }
            })
        },

        // 格式化日期
        formatDates() {
            this.formattedApplicationDate = { ...this.formData.applicationDate }
            this.formattedTransferDate = { ...this.formData.transferDate }
        }
    }
};
</script>
<style lang="scss" scoped>
.container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 24px;
    background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
    min-height: 100vh;
    position: relative;
}

.page-header {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 30px;
    padding: 20px;
    position: relative;
    background: rgba(255, 255, 255, 0.9);
    backdrop-filter: blur(10px);
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);

    h1 {
        font-size: 24px;
        color: #2c3e50;
        margin: 0;
        font-weight: 600;
        position: relative;
        padding-bottom: 10px;

        &::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 60px;
            height: 3px;
            background: linear-gradient(90deg, #409EFF, #67C23A);
            border-radius: 3px;
        }
    }
}

.back-button {
    position: absolute;
    left: 20px;
    top: 50%;
    transform: translateY(-50%);

    .el-button {
        padding: 8px 15px;
        font-size: 14px;
        border-radius: 6px;
        transition: all 0.3s ease;

        &:hover {
            transform: translateX(-2px);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
    }
}

.list-button {
    position: absolute;
    right: 20px;
    top: 50%;
    transform: translateY(-50%);

    .el-button {
        padding: 8px 15px;
        font-size: 14px;
        border-radius: 6px;
        transition: all 0.3s ease;

        &:hover {
            transform: translateX(2px);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
    }
}

.main-content {
    background: rgba(255, 255, 255, 0.9);
    backdrop-filter: blur(10px);
    border-radius: 12px;
    padding: 24px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
}

.form-actions {
    margin-bottom: 20px;
    display: flex;
    gap: 12px;
    justify-content: flex-end;

    .el-button {
        padding: 10px 24px;
        font-size: 14px;
        border-radius: 6px;
        transition: all 0.3s ease;

        &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }
    }
}

.investigation-form {
    table {
        width: 100%;
        border-collapse: separate;
        border-spacing: 0;
        border-radius: 8px;
        overflow: hidden;
        border: 1px solid #ebeef5;
        margin-bottom: 24px;

        td {
            padding: 12px;
            border: 1px solid #ebeef5;
            vertical-align: middle;

            &:first-child {
                background-color: rgba(248, 249, 250, 0.5);
                font-weight: 500;
                color: #2c3e50;
                width: 160px;
                text-align: center;
            }

            .el-input,
            .el-date-picker {
                width: 100%;
            }

            .el-input__inner {
                height: 32px;
                line-height: 32px;
                padding: 0 12px;
            }

            .el-textarea__inner {
                padding: 8px 12px;
                min-height: 80px;
                resize: vertical;
            }
        }

        tr:hover {
            background-color: rgba(64, 158, 255, 0.05);
        }
    }
}

.checkbox-group {
    display: flex;
    justify-content: center;
    gap: 10px;
    margin: 10px;
}

.form-footer {
    display: flex;
    justify-content: space-between;
    padding: 16px 0;
    color: #606266;
    font-size: 14px;
    border-top: 1px solid #ebeef5;
    margin-top: 20px;

    p {
        margin: 0;
    }
}

h3 {
    margin-bottom: 10px;
}

@media screen and (max-width: 768px) {
    .container {
        padding: 16px;
    }

    .page-header {
        padding: 16px;
        margin-bottom: 20px;

        h1 {
            font-size: 20px;
        }
    }

    .main-content {
        padding: 16px;
    }

    .form-actions {
        flex-direction: column;

        .el-button {
            width: 100%;
            margin: 4px 0;
        }
    }

    .investigation-form {
        table {
            td {
                padding: 8px;
                font-size: 13px;

                &:first-child {
                    width: 100px;
                }
            }
        }
    }

    .form-footer {
        flex-direction: column;
        text-align: center;
        gap: 8px;
    }
}

/* 打印样式 */
@media print {
    .container {
        margin: 0;
        padding: 0;
        background: none;
    }

    .page-header {
        margin-bottom: 20px;
        padding: 0;
        box-shadow: none;
        background: none;
    }

    .back-button,
    .list-button,
    .form-actions {
        display: none !important;
    }

    .main-content {
        padding: 0;
        background: none;
        box-shadow: none;
    }

    .investigation-form {
        table {
            border: 1px solid #000;

            td {
                border: 1px solid #000;
                padding: 8px;

                &:first-child {
                    background: none;
                }
            }
        }
    }

    .el-input__inner,
    .el-textarea__inner {
        border: none !important;
        padding: 0 !important;
    }

    .form-footer {
        border-top: none;
    }
}
</style>